<template>
  <div>
    <div class="address-box" v-for="(item, index) in addressList" :key="index">
      <div class="address-header">
        <span>{{item.receiver}}</span>
        <div class="address-action">

          <span type="primary"  @click="handleAddress(item, index)">
            <Icon type="edit" ></Icon> 编辑
          </span>
          <span @click="del(item.id)">
            <Icon type="trash-a"></Icon> 删除
          </span>
          <Modal
            v-model="editmodal"
            title="编辑收货地址"
            @on-ok="updateAddress(index)"
            width="700px">
            <Form ref="form" :model="formData" label-position="left" :label-width="100" :rules="ruleInline">
              <FormItem label="收件人" prop="receiver" class="itemRequired">
                <i-input v-model="formData.receiver" size="large"></i-input>
              </FormItem>
              <FormItem label="收件地区" prop="address" class="itemRequired">
                <v-distpicker
                  :province="areaSelect.province"
                  :city="areaSelect.city"
                  :area="areaSelect.area"
                  @selected="selectAddress"
                ></v-distpicker>
              </FormItem>
              <FormItem label="收件地址" prop="street" class="itemRequired">
                <i-input v-model="formData.street" size="large"></i-input>
              </FormItem>
              <FormItem label="手机号码" prop="phone" class="itemRequired">
                <i-input v-model="formData.phone" size="large"></i-input>
              </FormItem>
              <FormItem label="邮政编码" prop="zipCode" class="itemRequired">
                <i-input v-model="formData.zipCode" size="large"></i-input>
              </FormItem>
            </Form>
          </Modal>
        </div>
      </div>
      <div class="address-content">
        <p><span class="address-content-title"> 收 货 人 :</span> {{item.receiver}}</p>
        <p><span class="address-content-title">收货地区:</span> {{getAreaInfo(item.area)}}</p>
        <p><span class="address-content-title">收货地址:</span> {{item.street}}</p>
        <p><span class="address-content-title">邮政编码:</span> {{item.zipCode}}</p>
        <p><span class="address-content-title">手机号码:</span> {{item.phone}}</p>
      </div>
    </div>
  </div>


</template>

<script>
  import store from '@/vuex/store';
  import { mapState, mapActions } from 'vuex';
  import VDistpicker from "v-distpicker";
  // 收件人姓名
  const receiverValidate = (rule, value, callback) => {
    const reg = /^[\u4E00-\u9FA5\uf900-\ufa2d·s\-]{2,10}$/
    if (value === undefined || value === '') {
      callback(new Error('收件姓名不能为空'))
    } else if (!reg.test(value)) {
      callback(new Error('请输入2-10个汉字！'))
    } else {
      callback()
    }
  }
  // 街道
  const streetValidate = (rule, value, callback) => {
    const reg = /^[\u4E00-\u9FA5\uf900-\ufa2d·s\-]{2,20}$/
    if (value === undefined || value === '') {
      callback(new Error('收件地址不能为空'))
    } else if (!reg.test(value)) {
      callback(new Error('请输入2-20个汉字！'))
    } else {
      callback()
    }
  }
  // 电话号码
  const tellValidate = (rule, value, callback) => {
    const reg = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
    if (value === undefined || value === '') {
      callback(new Error('电话不能为空'))
    } else if (!reg.test(value)) {
      callback(new Error('请输入正确的电话号码'))
    } else {
      callback()
    }
  }
  // 邮政编码
  const zipcodeValidate = (rule, value, callback) => {
    const reg = /^[1-9]\\d{5}$/
    if (value === undefined || value === '') {
      callback(new Error('邮政编码不能为空'))
    } else if (reg.test(value)) {
      callback(new Error('请输入正确的邮政编码'))
    } else {
      callback()
    }
  }

  export default {
    name: 'MyAddress',
    inject: ["reload"],
    components: {
      VDistpicker
    },
    data() {
      return {
        areaSelect: {
          province: "湖北省",
          city: "宜昌市",
          area: "西陵区"
        },
        formData: {
          // address: '',
          street: '',
          phone: '',
          zipCode: '',
          area:'',
          uid: '',
          receiver: ''
        },
        ruleInline: {
          receiver: [{validator:receiverValidate, trigger: 'blur'}],
          street: [{validator:streetValidate, trigger: 'blur'}],
          zipCode: [{validator:zipcodeValidate, trigger: 'blur'}],
          phone: [{validator:tellValidate, trigger: 'blur'}]
        },
        addressList: [],
        editmodal:false,
      };
    },
    created:function() {
      let user = sessionStorage.getItem('loginInfo');
      let userinfo = (JSON.parse(user));
      const uid = userinfo.id;
      this.$http.get('/address/getAllAddress' + '/' + uid)
        .then(resp => {
          this.addressList = resp.data.data
        });
    },
    methods: {
      // 处理地址
      getAreaInfo(areaItem) {
        const areaStr = areaItem.split(',')
        areaItem = areaStr.join('')
        return areaItem
      },
      // 选择地址
      selectAddress(data) {
        this.areaSelect.province = data.province.value
        this.areaSelect.city = data.city.value
        this.areaSelect.area = data.area.value
        this.formData.area = this.areaSelect.province + ',' + this.areaSelect.city + ',' + this.areaSelect.area
      },
      // 修改地址信息
      handleAddress(itemData, index) {
        console.log(index)
        console.log("修改用户信息")
        this.formData = itemData
        // 清除表单验证
        this.$refs.form[index].resetFields()
        this.editmodal = true
      },
      // 保存修改
      updateAddress(index) {
        const addressData = this.formData;
        console.log(addressData)
        console.log("address=============")
        this.$refs.form[index].validate(valid => {
            if (valid) {
              const _this = this
              this.$http.put("/address/editAddress", addressData)
                .then(resp => {
                  _this.reload();
                }).cache(err => {
                  _this.$Message.error("修改失败")
                })
            }
        })
      },

      // 删除地址
      del(res) {
        const _this = this
        this.$http.delete('/address/del/' + res)
          .then(resp => {
            _this.$Message.success("删除成功")
            _this.$router.push({path: '/home'})
          }).cache(err => {
            _this.$Message.error("删除失败")
        })
      }
  },
   store
}
</script>

<style scoped>
  .address-box {
    padding: 15px;
    margin: 15px;
    border-radius: 5px;
    box-shadow: 0px 0px 5px #ccc;
  }

  .address-header {
    height: 35px;
    display: flex;
    justify-content: space-between;
    color: #232323;
    font-size: 18px;
  }

  .address-content {
    font-size: 14px;
  }

  .address-content-title {
    color: #999;
  }

  .address-action span {
    margin-left: 15px;
    font-size: 14px;
    color: #2d8cf0;
    cursor: pointer;
  }

  .itemRequired>>>label.ivu-form-item-label::before {
    content: '* ';
    color: #F56C6C;
    margin-right: 2px;
  }
</style>
